package main

import "fmt"

//[]int没有加长度，代表的是切片，不是数组
func updateSlice(s []int){
	//数组是值传递
	//但切片是引用传递
	//因为，切片是数组的视图
	s[0] = 100
}

func main() {
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	fmt.Println("arr[2:6] = ", arr[2:6])
	fmt.Println("arr[:6] = ", arr[:6])
	fmt.Println("arr[2:] = ", arr[2:])
	fmt.Println("arr[:] = ", arr[:])

	//切片作为函数的参数
	//切片：是数组的一个视图==>引用传递
	s1 := arr[2:]
	s2 :=arr[:]

	fmt.Println("before updateSlice: (s1)")
	fmt.Println("s1 = ", s1)
	fmt.Println("After updateSlice: (s1)")
	updateSlice(s1)
	fmt.Println("s1 = ", s1)
	fmt.Println("arr = ", arr)

	fmt.Println()

	fmt.Println("before updateSlice: (s2)")
	fmt.Println("s2 = ", s2)
	fmt.Println("After updateSlice: (s2)")
	updateSlice(s2)
	fmt.Println("s2 = ", s2)
	fmt.Println("arr = ", arr)

	fmt.Println()

	//reslice
	fmt.Println("before reslice:(s2)")
	fmt.Println("s2 = ", s2)
	s2 = s2[:5]
	fmt.Println("after reslice: (s2)")
	fmt.Println("s2 = ", s2)
	s2 = s2[2:]
	fmt.Println("after reslice: (s2)")
	fmt.Println("s2 = ", s2)
	fmt.Println("arr = ", arr)

	fmt.Println()

	fmt.Println("Extending Slice")
	arr[0], arr[2] = 0, 2
	fmt.Println("arr = ", arr)
	s1 = arr[2:6]
	s2 = s1[3:5]  //这里可以取到值，要特别注意，但单独s1[4]是报错的
	fmt.Println("s1 = ", s1)
	fmt.Println("s2 = ", s2)

	fmt.Printf("s1=%v, len(s1)=%d, cap(s1)=%d\n", s1, len(s1), cap(s1))
	fmt.Printf("s2=%v, len(s2)=%d, cap(s2)=%d\n", s2, len(s2), cap(s2))
	//fmt.Print(s1[3:7]) //会报错，超过range,这里的range指的是cap,而不是len

	//append
	//添加元素时，如果超越cap，系统会重新分配更大的底层数组
	//由于值传递的关系，必须接收append的返回值
	s3 := append(s2, 10)
	s4 := append(s3, 11)
	s5 := append(s4, 12)
	fmt.Println("s2=", s2)
	fmt.Println("s3=", s3)
	fmt.Println("s4=", s4)
	fmt.Println("s5=", s5)
	//s4 and s5 no longer view arr
	fmt.Println("arr=", arr)
	fmt.Printf("s2=%v, len(s2)=%d, cap(s2)=%d\n", s2, len(s2), cap(s2))
	fmt.Printf("s5=%v, len(s5)=%d, cap(s5)=%d\n", s5, len(s5), cap(s5))

}